package com.aco.party.web.controller.system;

import com.aco.party.util.PathUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;

import static com.aco.party.util.WebModelUtil.getBasePath;
import static com.aco.party.util.WebModelUtil.getImgPath;

/**
 * Created by WangShijun on 2016/5/14.
 */
@Controller
@RequestMapping("/system")
public class UEditorImageUpController {
    private final Logger logger = LoggerFactory.getLogger(getClass());


    final String SUCCESS = "SUCCESS";
    final String FAIL = "FAIL";

    @RequestMapping("ueditorImgUp")
    @ResponseBody
    public void ueditorImgUp(@RequestParam(value = "upfile", required = false) MultipartFile file, String pictitle,
                             HttpServletResponse response) throws Exception {
        logger.info("上传的图片大小是：" + (file.getSize() / 1024) + "KB");
        if (!file.isEmpty()) {
            String name = file.getOriginalFilename();
            String fileSuffix = PathUtil.getExtension(name);
            String oldName = name.replaceAll(fileSuffix, "");
            String fileName = UUID.randomUUID().toString();
            String newName = fileName + fileSuffix;
            String parentPath = getImgPath();
            logger.info("parentPath:" + parentPath);
            OutputStream out = new FileOutputStream(parentPath + newName);
            InputStream in = file.getInputStream();
            int length = 0;
            byte[] buf = new byte[1024];
            while ((length = in.read(buf)) != -1) {
                out.write(buf, 0, length);
            }
            in.close();
            out.close();
            String url = getBasePath() + "/system/getImg?imgId=" + newName;
            response.getWriter().print("{'original':'测试图片','url':'" + url + "','title':'" + pictitle + "','state':'" + SUCCESS + "'}");
        } else {
            response.getWriter().print("{'state':'" + FAIL + "'}");
        }
    }
}
